import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:scroll_to_index/scroll_to_index.dart';

import '../../dao/ImGroupDao.dart';
import '../../dao/ImSessionDao.dart';
import '../../pojo/ImPojo.dart';
import '../../service/ImGroupService.dart';
import '../../service/ImMessageSendService.dart';
import '../../util/DbUtil.dart';
import '../../util/HexColor.dart';
import '../../util/ImCacheFactory.dart';
import '../../util/ImConstant.dart';
import '../../util/ImSingleton.dart';
import '../../util/UiUtil.dart';
import '../bloc/SelectUsersCubit.dart';
import '../bloc/TransferMessageCubit.dart';
import '../view/SelectUsersView.dart';
import '../view/TransferMessageView.dart';
import 'TransferMessagePage.dart';

class TransferMessageWithUserPage extends StatefulWidget {
  const TransferMessageWithUserPage({super.key});

  @override
  State<StatefulWidget> createState() => _TransferMessageWithUserState();
}

class _TransferMessageWithUserState extends State<TransferMessageWithUserPage> {
  late TextEditingController _userTextEditingController;
  late AutoScrollController _userScrollController;
  late AutoScrollController _selectedUserScrollController;
  late FocusNode _userSearchFocusNode;

  @override
  void initState() {
    _userTextEditingController = TextEditingController();

    _userScrollController = AutoScrollController(
        viewportBoundaryGetter: () => Rect.fromLTRB(0, 0, 0, MediaQuery.of(context).padding.bottom),
        axis: Axis.vertical);

    _selectedUserScrollController = AutoScrollController(
        viewportBoundaryGetter: () => Rect.fromLTRB(0, 0, 0, MediaQuery.of(context).padding.bottom),
        axis: Axis.vertical);

    _userSearchFocusNode = FocusNode();
    _userSearchFocusNode.addListener(() {});
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    var selectUsersCubit = context.watch<SelectUsersCubit>();
    var transferMessageCubit = context.watch<TransferMessageCubit>();
    return BlocConsumer<TransferMessageCubit, TransferMessageState>(
        listener: (BuildContext context, TransferMessageState transferMessageState) {
      if (transferMessageState.showTransferPane && !transferMessageState.isTransferPaneFlush) {
        buildTransferPane(context, transferMessageCubit);
      }
    }, builder: (BuildContext context, TransferMessageState state) {
      return Scaffold(
        backgroundColor: ImConstant.IM_MAIN_BACKGROUND_COLOR,
        appBar: _buildAppBar(context, selectUsersCubit),
        body: const SelectUsersView(),
      );
    });
  }

  Widget _buildSelectGroupPane() {
    return ListTile(
      title: const Text('选择群聊'),
      onTap: () {},
    );
  }

  AppBar _buildAppBar(BuildContext context, SelectUsersCubit selectUsersCubit) {
    var color = selectUsersCubit.state.selectedUsers.isNotEmpty ? HexColor.fromHex("#32cd32") : Colors.grey.shade200;
    var buttonTitle = '完成';
    if (selectUsersCubit.state.selectedUsers.isNotEmpty) {
      buttonTitle = '完成(${selectUsersCubit.state.selectedUsers.length})';
    }
    return AppBar(
      leading: InkWell(
        child: const Icon(Icons.chevron_left),
        onTap: () {
          Navigator.of(context).pop();
        },
      ),
      title: const Text(
        '选择联系人',
        style: TextStyle(fontSize: ImConstant.IM_DEFAULT_SIZE, fontWeight: FontWeight.w500),
      ),
      toolbarHeight: ImConstant.IM_APP_BAR_HEIGTH,
      backgroundColor: ImConstant.IM_MAIN_BACKGROUND_COLOR,
      centerTitle: true,
      actions: [
        Padding(
          padding: const EdgeInsets.only(right: 10),
          child: OutlinedButton(
            style: OutlinedButton.styleFrom(
                backgroundColor: color,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(5.0),
                ),
                padding: const EdgeInsets.only(left: 2, right: 2, top: -5, bottom: -5)),
            onPressed: selectUsersCubit.state.selectedUsers.isEmpty ? null : () {
               _createNewGroupAndTransferMessage(context);
            },
            child: Text(buttonTitle),
          ),
        )
      ],
    );
  }

  @override
  void dispose() {
    _userScrollController.dispose();
    _userSearchFocusNode.dispose();
    _selectedUserScrollController.dispose();
    _userTextEditingController.dispose();
    super.dispose();
  }

  void _createNewGroupAndTransferMessage(BuildContext context) async {
    var selectUsersCubit = context.read<SelectUsersCubit>();
    var transferMessageCubit = context.read<TransferMessageCubit>();

    var state = selectUsersCubit.state;
    if (state.selectedUsers.isEmpty) return;

    var userId = ImSingleton.getInstance().session.userId!;
    var users = state.selectedUsers;

    ImSession? imSession = null;
    if (users.length > 1) {
      // 选中多人则需要建群
      var loginUser = await ImCacheFactory.getInstance().getImUser(userId);
      var existed = users.contains(loginUser);
      if (!existed) {
        users.add(loginUser!);
      }

      // 检查选择的用户是否已是一个群，否则重新建一个群
      var groupDao = ImGroupDao();
      var groupId = await groupDao.getGroupByUserIds(users.map((user)=>user.userId).toList());
      if (groupId != null) {
        var sessionDao = ImSessionDao();
        var group = await groupDao.getById(groupId);
        imSession = await sessionDao.getByGroupCodeAndUserId(group!.code, userId);
      } else {
        var groupService = ImGroupService();

        imSession = groupService.buildImGroup(userId, users);
        await groupService.createImGroup(imSession);

        UiUtil.uiShowSession(imSession);

        await groupService.rpcCreateGroup(imSession);
      }
    } else {
      var sessionDao = ImSessionDao();
      var dbSession = await sessionDao.getByUserId(userId, userId, users[0].userId);
      if (dbSession != null) {
        imSession = dbSession;
      } else {
        imSession = ImSession.buildWithUser(userId, users[0]);
        await sessionDao.batchInserts([imSession]);

        UiUtil.uiShowSession(imSession);
      }
    }
    transferMessageCubit.add(TransferMessageSelectSessionEvent(imSession!));
  }

  Future<List<ImMessage>> buildImMessages(
      ImSession session, List<ImMessage> imMessages, ImMessageSendService messageSendService) async {
    var result = <ImMessage>[];
    for (var imMessage in imMessages) {
      var newMessage = await buildImMessage(session, imMessage, messageSendService);
      result.add(newMessage);
    }
    return result;
  }

  Future<ImMessage> buildImMessage(ImSession session, ImMessage imMessage, ImMessageSendService messageSendService) async {
    var content = imMessage.content ?? '';
    var imMessageType = imMessage.messageType;
    var refMessages = imMessage.refMessages;

    var message = await messageSendService.buildMessage(session, content, imMessageType, refMessages);
    return message;
  }
}

enum SelectType {
  simple('单选', '选择多个聊天'),
  multiple('多选', '选择一个聊天群'),
  ;

  final String name;
  final String title;

  const SelectType(this.name, this.title);

  SelectType switchSelectType() {
    if (this == simple) return multiple;
    return simple;
  }
}
